﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Orchard.ContentManagement;
using Orchard.Core.Contents;
using Orchard.Security;
using Orchard.Mvc.Extensions;
using Orchard.UI.Notify;
using Orchard.Localization;

namespace Piedone.ContentCopy.Controllers
{
    public class CopyController : Controller
    {
        private readonly IContentManager _contentManager;
        private readonly IAuthorizer _authorizer;
        private readonly INotifier _notifier;

        public Localizer T { get; set; }


        public CopyController(IContentManager contentManager, IAuthorizer authorizer, INotifier notifier)
        {
            _contentManager = contentManager;
            _authorizer = authorizer;
            _notifier = notifier;

            T = NullLocalizer.Instance;
        }


        [HttpPost]
        public ActionResult Clone(int id, string returnUrl)
        {
            // Mostly taken from: http://orchard.codeplex.com/discussions/396664
            var contentItem = _contentManager.GetLatest(id);

            if (contentItem == null) return HttpNotFound();
            if (!_authorizer.Authorize(Permissions.EditContent, contentItem)) return new HttpUnauthorizedResult();

            var importContentSession = new ImportContentSession(_contentManager);

            var element = _contentManager.Export(contentItem);
            var elementId = element.Attribute("Id");
            var copyId = elementId.Value + "-copy";
            elementId.SetValue(copyId);
            var status = element.Attribute("Status");
            if (status != null) status.SetValue("Draft"); // So the copy is always a draft.

            importContentSession.Set(copyId, element.Name.LocalName);

            _contentManager.Import(element, importContentSession);

            _notifier.Information(T("Successfully cloned. The copy was saved as a draft."));

            return this.RedirectLocal(returnUrl);
        }
    }
}